package com.ycsj.goldmedalnewconcept.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mob.MobSDK;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.ZhiboListResponse;
import com.ycsj.goldmedalnewconcept.constant.Constant;

import java.io.IOException;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnCompletionListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnErrorListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnPreparedListener;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.widget.media.IjkVideoView;

//直播全屏
public class ZhiboScreenActivity extends Activity implements OnClickListener {

	private ImageView iv_back;
	private String mVideoPath;
	private IjkVideoView mVideoView;
	private boolean mBackPressed;
	private ImageView iv_all;
	private ImageView iv_share;
	private int p;
	private String v_id;
	private String time;
	private String temptime;
	private String title;
	private String picurl;
	private LinearLayout llLoading;
	private LinearLayout ll_click;
	private FrameLayout fl_bg;
	private FrameLayout fl_bg2;
	private int count;
	private long firClick;
	private long secClick;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zhibo_screen);
		 mVideoPath = getIntent().getStringExtra("stream_addr");
		p = getIntent().getIntExtra("p", 0);
		v_id = getIntent().getStringExtra("v_id");
		initView();
		setOnListener();
		initData();
	}

	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		initData();
		super.onRestart();
	}

	@Override
	public void onBackPressed() {
		mBackPressed = true;
		super.onBackPressed();
	}

	@Override
	protected void onStop() {
		super.onStop();

		if (mBackPressed || !mVideoView.isBackgroundPlayEnabled()) {
			mVideoView.stopPlayback();
			mVideoView.release(true);
			mVideoView.stopBackgroundPlay();
		} else {
			mVideoView.enterBackground();
		}
		IjkMediaPlayer.native_profileEnd();
	}

	private void initView() {
		// TODO Auto-generated method stub
		iv_back = (ImageView) findViewById(R.id.iv_back);
		iv_all = (ImageView) findViewById(R.id.iv_all);
		iv_share = (ImageView) findViewById(R.id.iv_share);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		ll_click = (LinearLayout) findViewById(R.id.ll_click);
		fl_bg = (FrameLayout) findViewById(R.id.fl_bg);
		fl_bg2 = (FrameLayout) findViewById(R.id.fl_bg2);
	}

	private void initData() {
		// http://192.168.0.164:8080/ycsj_count/MessageCenter?type=110

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "110");
		Request request = new Request.Builder()
				.url(Constant.ycsj_count_MessageCenter)
				// .url("http://pm.moregolden.com/ycsj_count/MessageCenter")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络中断，请检查您的网络连接", Toast.LENGTH_SHORT)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				ZhiboListResponse fromJson = gson.fromJson(
						arg0.body().string(), ZhiboListResponse.class);
				mVideoPath = fromJson.list.get(p).url;
				temptime = fromJson.list.get(p).playtime;
				time = temptime.substring(0, 16);
				title = fromJson.list.get(p).title;
				picurl = fromJson.list.get(p).pic;
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						player();
					}
				});
			}

			private void player() {
				// TODO Auto-generated method stub
				mVideoView = (IjkVideoView) findViewById(R.id.video_view);
				IjkMediaPlayer.loadLibrariesOnce(null);
				IjkMediaPlayer.native_profileBegin("libijkplayer.so");
				if (mVideoPath != null) {
					 mVideoView.setVideoPath(mVideoPath);
//					mVideoView
//					.setVideoPath("rtmp://live.hkstv.hk.lxdns.com/live/hks");
				}

				mVideoView.start();

				mVideoView.setOnErrorListener(new OnErrorListener() {

					@Override
					public boolean onError(IMediaPlayer mp, int what, int extra) {
						// TODO Auto-generated method stub
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								llLoading.setVisibility(View.VISIBLE);
								fl_bg.setVisibility(fl_bg.VISIBLE);
								fl_bg2.setVisibility(fl_bg2.VISIBLE);
								fl_bg.setBackgroundResource(R.color.black);
								fl_bg2.setBackgroundResource(R.color.black);

								initData();
								Log.e("test", "直播报错");
							}
						});

						return false;
					}
				});

				mVideoView.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(IMediaPlayer mp) {
						// TODO Auto-generated method stub
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								llLoading.setVisibility(View.VISIBLE);

								initData();
							}
						});
					}
				});

				mVideoView.setOnPreparedListener(new OnPreparedListener() {

					@Override
					public void onPrepared(IMediaPlayer mp) {
						// TODO Auto-generated method stub
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								llLoading.setVisibility(View.GONE);
								fl_bg.setBackgroundResource(R.color.base_black);
								fl_bg2.setBackgroundResource(R.color.base_black);
								fl_bg.setVisibility(fl_bg.GONE);
								fl_bg2.setVisibility(fl_bg2.GONE);

								Log.e("test", "直播完成准备");
							}
						});
					}
				});
			}
		});
	}

	private void setOnListener() {
		iv_back.setOnClickListener(this);
		iv_all.setOnClickListener(this);
		iv_share.setOnClickListener(this);
		ll_click.setOnClickListener(this);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent(this, ZhiboActivity.class);
			intent.putExtra("p", p);
			startActivity(intent);
			finish();
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			Intent intent = new Intent(this, ZhiboActivity.class);
			intent.putExtra("p", p);
			intent.putExtra("v_id", v_id);
			startActivity(intent);
			finish();
			break;
		case R.id.iv_share:

			clickShare(v);
			break;

		case R.id.iv_all:
			Intent intent1 = new Intent(this, ZhiboActivity.class);
			intent1.putExtra("p", p);
			intent1.putExtra("v_id", v_id);
			startActivity(intent1);
			finish();

			break;
		case R.id.ll_click:
			count++;
			if (count == 1) {
				firClick = System.currentTimeMillis();

			} else if (count == 2) {
				secClick = System.currentTimeMillis();
				if (secClick - firClick < 1000) {
					// 双击事件
					intent = new Intent(this, ZhiboActivity.class);
					intent.putExtra("p", p);
					intent.putExtra("v_id", v_id);
					startActivity(intent);
					finish();
				}
				count = 0;
				firClick = 0;
				secClick = 0;
			}
			break;
		}
	}

	private void clickShare(View v) {

		// TODO Auto-generated method stub
		MobSDK.init(ZhiboScreenActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {
				if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					String url = "http://m.moregolden.com:36356/videoLive/video.html?vid="
							+ v_id;

					// String title = title;
					int unicodeJoy = 0x1F44D;
					String emojiString = new String(Character
							.toChars(unicodeJoy));
					paramsToShare
							.setTitleUrl("http://m.moregolden.com:36356/videoLive/video.html?vid="
									+ v_id);
					// paramsToShare.setTitleUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					paramsToShare.setTitle(title);
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText("金牌新概念邀您收听直播\n" + "时间：" + time);
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare.setImageUrl(picurl);
					// paramsToShare.setImageData(mBitmap);
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare
							.setUrl("http://m.moregolden.com:36356/videoLive/video.html?vid="
									+ v_id);
					// paramsToShare.setUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					// paramsToShare.setSite(getString(R.string.app_name));
					paramsToShare.setSite("金牌君");
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare
							.setSiteUrl("http://m.moregolden.com:36356/videoLive/video.html?vid="
									+ v_id);
					// paramsToShare.setSiteUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);

				} else {
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					paramsToShare
							.setTitleUrl("http://m.moregolden.com:36356/videoLive/video.html?vid="
									+ v_id);
					// paramsToShare.setTitleUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					paramsToShare.setTitle(title);
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText("金牌新概念邀您收听直播\n" + "时间：" + time);
					
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare.setImageUrl(picurl);

					// paramsToShare.setImageData(mBitmap);
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare
							.setUrl("http://m.moregolden.com:36356/videoLive/video.html?vid="
									+ v_id);
					// paramsToShare.setUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite("金牌君");
					// paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare
							.setSiteUrl("http://m.moregolden.com:36356/videoLive/video.html?vid="
									+ v_id);

				}
			}
		});

		// 启动分享GUI
		oks.show(this);
	}

}
